<!DOCTYPE html>
<html lang="en">
<head>
<title>切换城市</title>
<meta charset="utf-8">
<link rel="shortcut icon" href="/staticFile/images/userIndex/favicon.ico" />
<link type="text/css" rel="stylesheet" href="/staticFile/css/userIndex/cityList.css">
<script type="text/javascript" src="/staticFile/js/plugins/jquery/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="/staticFile/js/common/commonUtil.js"></script>
<script type="text/javascript">
//添加所有省份信息
let allProvince = '110000,北京;120000,天津;130000,河北;140000,山西;150000,内蒙古;210000,辽宁;220000,吉林;230000,黑龙江;310000,上海;320000,江苏;330000,浙江;340000,安徽;350000,福建;360000,江西;370000,山东;410000,河南;420000,湖北;430000,湖南;440000,广东;450000,广西;460000,海南;500000,重庆;510000,四川;520000,贵州;530000,云南;540000,西藏;610000,陕西;620000,甘肃;630000,青海;640000,宁夏;650000,新疆;710000,台湾;810000,香港;820000,澳门';
let provinceArray = allProvince.split(';'), provinceDiv = '', provinceSpan = '';
for (let g = 0; g < provinceArray.length; g ++) {
    if (g % 12 == 0 || (g == provinceArray.length - 1)) {
        provinceDiv += '<div class="province-col">' + provinceSpan + '</div>';
        provinceSpan = '';
    }
    let pCodeName = provinceArray[g].split(',');
    provinceSpan += '<span class="mt-province" id="' + pCodeName[0] + '">' + pCodeName[1] + '</span>';
}
let isZh = false, searchKey = '';//isZh:是否中文输入法
$(function () {
    $('.provinces-wrapper').append(provinceDiv);
    //设置搜索框右边距
    let leftBorderWidth = ($('body').width() - $('.city-list-body').width()) / 2 + 'px';
    $('.search-title').css('margin-left', leftBorderWidth);
    $('.provinces-list a').click(function () {
        $('.selected-province').removeClass();
        this.className = 'selected-province';
    });

    $('.choose-province').click(function (e) {
        $('.mt-provinces').show();
        //点击其它地方则隐藏
        $(document).one("click", function () {
            $(".mt-provinces").hide();
        });
        e.stopPropagation();
    });
    $('.mt-province').click(function (e) {
        listAllCities(this.id, '');
        $(".mt-provinces").hide();
        $('#showProvince').text(this.innerText);
        $('#showCity').text('城市');
        e.stopPropagation();
    });
    $('.choose-city').click(function (e) {
        $('.mt-cities').show();
        //点击其它地方则隐藏
        $(document).one("click", function () {
            $(".mt-cities").hide();
        });
        e.stopPropagation();
    });
    $('.search-key').keyup(function () {
        let searchKey = this.value;
        if (!isZh && !isNull(searchKey)) {
            window.setTimeout(function () {
                if (searchKey == V('searchKey')) {
                    listAllCities('', V('searchKey'));
                }
            }, 500);
        }
        if (isNull(searchKey)) {
            $('.search-city-container').hide();
        }
    });
    let iptSearchKey = I('searchKey');
    addEvent(iptSearchKey, 'compositionstart', function (e) {
        e = e || window.event;
        if (isZh && V('searchKey')) {
            listAllCities('', V('searchKey'));
        }
        isZh = true;
    });
    addEvent(iptSearchKey, 'compositionend', function (e) {
        e = e || window.event;
        if (isZh && V('searchKey')) {
            listAllCities('', V('searchKey'));
        }
        isZh = false;
    });
    listCitiesByWords();
    $('.letter').click(function () {
        $('.selected-word').each(function () {
            $(this).removeClass('selected-word');
        });
        $(this).addClass('selected-word');
        let word = $(this).text();
        let thisTop = $('#city' + word).offset().top;
        window.scrollTo(0, thisTop);
    });
});

/**
 * 获取城市数据
 * @param provinceCode 省编码
 * @param cityPinYinOrName 城市拼音首字母或名字
 */
function listAllCities(provinceCode, cityPinYinOrName) {
    let cityJsonStr = localStorage.getItem('city_by_' + provinceCode), fullPinyin = '', sCityName = '';
    if (!isNull(cityJsonStr)) {
        appendCity(cityJsonStr);
        return;
    }
    if (!isNull(cityPinYinOrName)) {
        let isHaveZh = false, isHaveEn = false, isLoad = true,//是否需要加载
            pinYinNameArray = cityPinYinOrName.split('');
        for (let g = 0; g < pinYinNameArray.length; g++) {
            //如果不是汉字，也不是字母，则不加载
            let zhReg = /[\u4e00-\u9fa5]/g, enReg = /[a-zA-Z]/g;
            let isZh = !zhReg.test(pinYinNameArray[g]), isEn = !enReg.test(pinYinNameArray[g]);
            if (isZh && isEn) {
                isLoad = false;
                break;
            } else if (isZh) {
                isHaveZh = true;
            } else if (isEn) {
                isHaveEn = true;
            }
            if (isHaveZh && isHaveEn) {
                isLoad = false;
                break;
            }
        }
        if (!isLoad) {
            appendSearchNoCity();
            return;
        }
        if (!isHaveZh && isHaveEn) {
            sCityName = cityPinYinOrName;
        } else {
            fullPinyin = cityPinYinOrName.toUpperCase();
        }
    }

    $.ajax({
        type: "POST",
        url: '/userIndex/listAllCities',
        data: {provinceCode: provinceCode, fullPinyin: fullPinyin, cityName: sCityName},
        dataType: 'json',
        async: false,
        success: function (result) {
            if (result != null && result.length > 0) {
                for (let g = 0; g < result.length; g++) {
                    delete result[g].provinceCode;
                }
                cityJsonStr = JSON.stringify(result).toString();
                if (!isNull(provinceCode)) {
                    appendCity(cityJsonStr);
                    localStorage.setItem('city_by_' + provinceCode, cityJsonStr);
                } else {
                    appendSearchCity(cityJsonStr);
                }
            } else if (isNull(provinceCode)) {
                appendSearchNoCity();
            }
        },
        error: function () {
            alert('当前系统繁忙,请稍后再试');
        }
    });
}

/**
 * 添加城市
 * @param cityJsonStr
 */
function appendCity(cityJsonStr) {
    let cityObjArray = eval('(' + cityJsonStr + ')'), cityDiv = '', citySpan = '', coLen = cityObjArray.length;
    for (let g = 0; g < coLen; g++) {
        if (g % 12 == 0 || (g == coLen - 1)) {
            cityDiv += '<div class="city-col">' + citySpan + '</div>';
            citySpan = '';
        }
        citySpan += '<a id="' + cityObjArray[g].cityCode + '" class="mt-city">' + cityObjArray[g].cityName + '</a>';
    }
    //如果选择的只有一个城市（如直辖市），则重新添加城市
    if (coLen == 1){
        cityDiv = '<div class="city-col">' + citySpan + '</div>';
    }
    $('.cities-wrapper').empty().append(cityDiv);
    $('.mt-city').click(function (e) {
        $(".mt-cities").hide();
        e.stopPropagation();
        $('#showCity').text(this.innerText);
        loadSelectedCity(this);
    });
}

/**
 * 添加城市
 * @param cityJsonStr
 */
function appendSearchCity(cityJsonStr) {
    let scw = $('.search-city-wapper');
    let cityObjArray = eval('(' + cityJsonStr + ')'), cityArr = [];
    for (let g = 0; g < cityObjArray.length; g++) {
        cityArr.push('<a id="' + cityObjArray[g].cityCode + '">' + cityObjArray[g].cityName + '</a>');
    }
    scw.empty().append(cityArr.join(''));
    $('.search-city-container').show();
    $('.search-city-wapper a').click(function () {
        loadSelectedCity(this);
    });
}

/**
 * 添加没有搜索到城市提示
 */
function appendSearchNoCity() {
    let noCityWap = $('.search-city-wapper');
    noCityWap.empty();
    noCityWap.append('<span>暂没找到对应的城市</span>');
    $('.search-city-container').show();
}

function addEvent(el, type, fn) {
    if (el.addEventListener) {
        el.addEventListener(type, fn, false);
    } else {
        el.attachEvent('on' + type, fn);
    }
}

/**
 * 获取城市数据
 */
function listCitiesByWords() {
    var cityByWordJson = localStorage.getItem('cityByWord');
    if (!isNull(cityByWordJson)) {
        appendCityByWords(cityByWordJson);
        return;
    }
    $.ajax({
        type: "POST",
        url: '/userIndex/listCitiesByWords',
        dataType: 'json',
        async: false,
        success: function (result) {
            if (result != null && result.length > 0) {
                cityByWordJson = JSON.stringify(result).toString();
                appendCityByWords(cityByWordJson);
                localStorage.setItem('cityByWord', cityByWordJson);
            }
        },
        error: function () {
            alert('当前系统繁忙,请稍后再试');
        }
    });
}

/**
 * 添加按拼音首字母
 * @param cityByWords
 */
function appendCityByWords(cityByWords) {
    let cityByWordsArray = eval('(' + cityByWords + ')'), cityByWordStr = '';
    for (let g = 0; g < cityByWordsArray.length; g++) {
        let cityObj = cityByWordsArray[g];
        let w = cityObj.words;
        cityByWordStr += '<div class="city-area" id="city' + w + '"><span class="city-label">' + w + '</span><span class="cities">',
            codeNameArray = cityObj.codeAndName.split(',');
        for (let q = 0; q < codeNameArray.length; q++) {
            let codeName = codeNameArray[q].split('|');
            cityByWordStr += '<a id="' + codeName[0] + '" class="city">' + codeName[1] + '</a>';
        }
        cityByWordStr += '</span></div>';
        $('.word-list').append('<span class="letter">' + w + '</span>');
    }
    $('.city-list').prepend(cityByWordStr);
    $('.city,.hot-city-list a').click(function () {
        loadSelectedCity(this);
    });
}

/**
 * 加载选择了的城市
 */
function loadSelectedCity(obj) {
    localStorage.setItem('LAST_CITY_ID_KEY', obj.id);
    localStorage.setItem('LAST_CITY_NAME_KEY', obj.text);
    history.go(-1);
    //location.href = location.href.split('userPages')[0];// + '?code=' + obj.id + '&name=' + escape(obj.text);
}
</script>
</head>
<body>
<header class="search-header">
    <strong class="search-title">切换服务城市</strong>
</header>
<div class="city-by-province">
    <h3>按省份选择:</h3>
    <div class="choose-wrap">
        <div class="choose-province">
            <span id="showProvince">省份</span>
            <div class="select-icon">
                <span></span>
            </div>
            <div class="mt-provinces">
                <div class="provinces-wrapper clearfix"></div>
            </div>
        </div>

        <div class="choose-city allow">
            <span id="showCity">城市</span>
            <div class="select-icon">
                <span></span>
            </div>
            <div class="mt-cities">
                <div class="cities-wrapper clearfix"></div>
            </div>
        </div>

        <div class="city-search">
            直接搜索：<input id="searchKey" class="search-key" type="text" placeholder="城市名/拼音首字母">
            <!--<button class="btn-city-search">
                <div class="btn-icon"></div>
            </button>-->
            <div class="search-city-container">
                <div class="search-city-wapper"></div>
            </div>
        </div>
    </div>
    <hr class="horizontal-line">
    <h3>热门城市：</h3>
    <div class="hot-city-list">
        <a id="110100">北京</a><a id="310100">上海</a><a id="330100">杭州</a><a id="420100">武汉</a>
        <a id="120100">天津</a><a id="440100">广州</a><a id="440300">深圳</a><a id="510100">成都</a>
        <a id="430100">长沙</a><a id="500100">重庆</a><a id="320100">南京</a><a id="610100">西安</a>
    </div>
</div>
<div class="city-list-body">
    <h3>拼音首字母选择：</h3>
    <p class="word-list"></p>
</div>
<div class="city-list">
    <span class="back"><input type="button" onclick="javascript:history.go(-1);" class="btn-back" value=" 返  回 "></span>
</div>
</body>
</html>